import React from 'react'
import { useSelector, RootState } from '@/redux/index'
import { useLocation, Navigate } from 'react-router-dom'
import { allRoutes } from '@/routes/index'
import { searchRoute } from '@/utils/util'
/**
 * @description 路由守卫组件
 * */

const AuthRouter = (props: { children: JSX.Element }) => {
  const { token } = useSelector((state: RootState) => state.global)
  // useLocation 返回当前url的location对象
  const { pathname } = useLocation()

  const route = searchRoute(pathname, allRoutes)

  // 1.判断当前路由是否需要访问权限
  if (!route.meta?.requiresAuth) return props.children

  // 2.判断是否有token
  if (!token) return <Navigate to="/login" replace />

  // 当前账号有权限且有token，返回Router，正常访问页面
  return props.children
}

export default AuthRouter
